<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 19-5-13 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\controllers;

use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 认证控制器
 * Authenticator controller
 */
class AuthController extends BaseController
{
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                //配置API接口认证方式
                HttpBearerAuth::class
            ],
        ];
        // HTTP 头发送目前的速率限制信息
        $behaviors['rateLimiter']['enableRateLimitHeaders'] = false;
        return $behaviors;
    }

    /**
     * 检测post请求
     * 如果非post请求，发送4405代码
     * @return mixed
     */
    public function validateIsPost()
    {
        if (!Yii::$app->getRequest()->getIsPost()) {
            $response = Yii::$app->getResponse();
            $response->data = Yii::$app->api->send(4405);
            $response->send();
        }
        return true;
    }
    /**
     * 退出
     * @return mixed
     * @throws \Throwable
     */
    public function actionLogout()
    {
        $user = Yii::$app->getUser()->getIdentity();
        $user->access_token_expire = 0;
        $user->save();
        return Yii::$app->api->success();
    }
}
